package com.seecode;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;

import com.seecode.Database.History;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;


/**
 * Created by Administrator on 2017/10/18.
 */

public class Utils {

    private static Context  mConText;
    private static MainActivity main;

    public static void init(MainActivity m){

        mConText=m;
        main = m;
    }


    public static boolean getPreBoolValues(String key){

        return PreferenceManager.getDefaultSharedPreferences(mConText).getBoolean(key, false);

    }
    public static void setPreBoolValues(String key,boolean value){

        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(mConText).edit();
        editor.putBoolean(key,value);
        editor.apply();


    }
    public static String getPreStrValues(String key){

        return PreferenceManager.getDefaultSharedPreferences(mConText).getString(key, "null");

    }
    public static void  setPreStrValues(String key,String value){

        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(mConText).edit();
        editor.putString(key,value);
        editor.apply();

    }

    public static void saveHistory(String name) {

            int lastS = name.lastIndexOf("/");

            String classNme=name.substring(lastS+1);
        History hi = new History();
        hi.setClassName(classNme);
        hi.setFilePath(name);
        hi.save();

    }
    public static  void  saveFile(String fileName,String content){
        try {
            File f = new File(fileName);
            if (!f.exists()) {
                f.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(f);
            fos.write(content.getBytes());
        }catch (Exception e){

            e.printStackTrace();
        }


    }
    public static void seeHistory(){

        Intent intent  = new Intent(mConText, HistoryActivity.class);
        mConText.startActivity(intent);

    }
    public static void showToast(final String name){
        if(Looper.getMainLooper().getThread() == Thread.currentThread()) {
            Toast.makeText(mConText, name, Toast.LENGTH_SHORT).show();
        }else{

            main.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showToast(name);
                }
            });
        }
    }
    public static  void loadUrl(String name){

        int pos =name.indexOf("@");
        String filePath =name.substring(pos+1);
        main.loadCode(filePath);
    }
    public static  void loadUrl2(String path){


        main.loadCode(path);
    }
    public static String readAssetsContent(String fileName){
        String content="readfailed";
        try{
            InputStream fis = mConText.getClass().getResourceAsStream(fileName);
            //InputStream fis = this.getBaseContext().getAssets().open(fileName);
            //this getAsstes failed
            int length = fis.available();
            Log.i("file long",""+length);
            byte[] buffer = new byte[length];
            fis.read(buffer);
            content = new String(buffer,"utf-8");
            //Logs.i("readAssets:"+fileName+":"+content);
            fis.close();


        }catch (Exception e){

            e.printStackTrace();
        }
        return content;


    }

    public  static void readFun(String name){

        main.readFun(name);
    }

    public  static void  remountDevPermission(){

        //this is so deep to change systemdev too violent carefull budy
            String cmd="mount -o remount,rw rootfs" ;// this change dir permission
            //if you want change file  like chmod 777 ./* but not sugession
          exeAsRoot(cmd);
    }
    public static boolean exeAsRoot(String cmd){

        Process process = null;
        DataOutputStream os = null;
        DataInputStream  in = null;

        try {

            process = Runtime.getRuntime().exec("su "); //切换到root帐号
            os = new DataOutputStream(process.getOutputStream());
            in = new DataInputStream(process.getInputStream());
            os.writeBytes(cmd + "\n");
            Logs.i("cmd:"+cmd);
            os.writeBytes("exit\n");
            os.flush();
            //process.waitFor();


            process.waitFor();

        } catch (Exception e) {
            return false;
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                process.destroy();
            } catch (Exception e) {
            }
        }
        return true;
    }

    public  static void changeFilePermission(String fileName){
        String cmd="chmod u+r "+fileName;
        exeAsRoot(cmd);
    }
    public static void changePathPermission(String path){
        upgradePathPermission(path);

    }
    public static boolean  upgradePathPermission(String path) {

        String cmd ="chmod u+rw "+path;

        return exeAsRoot(cmd);
    }
    public static boolean  upgradefilesPermission(String path) {
        if(path.equals("/")) {

            path = "";
        }
            String cmd ="chmod 777 "+path+"/*";



        return exeAsRoot(cmd);
    }


    public static String readFileContent(String fileName){
        String content="file read failed";
        try{

            File file = new File(fileName);
            if(!file.canRead()){

                Utils.changeFilePermission(file.getPath());
            }
            FileInputStream fis = new FileInputStream(file);
            int length = fis.available();
            byte[] buffer = new byte[length];
            fis.read(buffer);
            content = new String(buffer,"utf-8");
            Logs.i("utils file size is:"+length/1000+"KB");
            if(length < 10000){
                Logs.i("main file is small than 10KB");
            }else{
                Logs.i("main read file too big i not print it");
            }

            fis.close();


            return content;
        }catch (Exception e){
            e.printStackTrace();


            Utils.showToast("读取失败");

        }

        return "null";


    }

    public  static void fileCheck(String fileName){

        String[] str ={".java",".cpp",".c",".txt",".php",".js"};
        int count =str.length;
        boolean isok=false;
        for(int i=0;i< count;i++){

            if(fileName.indexOf(str[i]) >=0){
                isok = true;
                break;
            }
        }
        if(!isok){

            showToast("this file not suggestion to read Maybe broken __-----__ ");
        }
    }

}
